import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import FormData from 'form-data';
import fetch from 'node-fetch';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const API_URL = 'http://localhost:3000';

/**
 * 测试健康检查
 */
async function testHealth() {
  console.log('🏥 测试健康检查...');
  try {
    const response = await fetch(`${API_URL}/health`);
    const data = await response.json();
    console.log('✅ 健康检查成功:', data);
    return true;
  } catch (error) {
    console.error('❌ 健康检查失败:', error.message);
    return false;
  }
}

/**
 * 测试文件上传识别
 */
async function testFileUpload(imagePath) {
  console.log(`\n📤 测试文件上传识别: ${path.basename(imagePath)}`);
  
  try {
    const formData = new FormData();
    formData.append('image', fs.createReadStream(imagePath));

    const response = await fetch(`${API_URL}/api/recognize`, {
      method: 'POST',
      body: formData
    });

    const data = await response.json();
    
    if (data.success) {
      console.log('✅ 识别成功!');
      console.log(`   识别到 ${data.count} 个二维码:`);
      data.data.forEach((qr, index) => {
        console.log(`   [${index + 1}] ${qr.text}`);
      });
    } else {
      console.log('❌ 识别失败:', data.error);
    }
    
    return data;
  } catch (error) {
    console.error('❌ 请求失败:', error.message);
    return null;
  }
}

/**
 * 测试 Base64 识别
 */
async function testBase64(imagePath) {
  console.log(`\n🔤 测试 Base64 识别: ${path.basename(imagePath)}`);
  
  try {
    const imageBuffer = fs.readFileSync(imagePath);
    const base64Image = `data:image/png;base64,${imageBuffer.toString('base64')}`;

    const response = await fetch(`${API_URL}/api/recognize-base64`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ image: base64Image })
    });

    const data = await response.json();
    
    if (data.success) {
      console.log('✅ 识别成功!');
      console.log(`   识别到 ${data.count} 个二维码:`);
      data.data.forEach((qr, index) => {
        console.log(`   [${index + 1}] ${qr.text}`);
      });
    } else {
      console.log('❌ 识别失败:', data.error);
    }
    
    return data;
  } catch (error) {
    console.error('❌ 请求失败:', error.message);
    return null;
  }
}

/**
 * 运行所有测试
 */
async function runAllTests() {
  console.log('🧪 开始测试二维码识别 API\n');
  console.log('='.repeat(60));

  // 测试健康检查
  const healthOk = await testHealth();
  if (!healthOk) {
    console.log('\n⚠️  服务器未启动，请先运行: npm start');
    return;
  }

  console.log('\n' + '='.repeat(60));

  // 获取测试图片
  const testImagesDir = path.join(__dirname, 'test-images');
  const testImages = fs.readdirSync(testImagesDir)
    .filter(file => file.endsWith('.png'))
    .map(file => path.join(testImagesDir, file));

  if (testImages.length === 0) {
    console.log('\n⚠️  没有找到测试图片，请先运行: node create-test-qrcode.js');
    return;
  }

  // 测试每个图片
  for (const imagePath of testImages) {
    await testFileUpload(imagePath);
  }

  console.log('\n' + '='.repeat(60));

  // 测试 Base64 方式（只测试第一张图片）
  if (testImages.length > 0) {
    await testBase64(testImages[0]);
  }

  console.log('\n' + '='.repeat(60));
  console.log('\n✨ 测试完成！\n');
}

// 运行测试
runAllTests();

